package com.cheyun.netsalev3.viewmodel

import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.DatePicker
import android.widget.TimePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.bean.CarBrandParam
import com.cheyun.netsalev3.bean.DaoDianDetailsParam
import com.cheyun.netsalev3.bean.DialogParam
import com.cheyun.netsalev3.bean.basedata.Member
import com.cheyun.netsalev3.bean.drive.DriveArchiveData
import com.cheyun.netsalev3.bean.drive.ReserveInfo
import com.cheyun.netsalev3.bean.order.OrderKeliuData
import com.cheyun.netsalev3.repository.EditCustomStoreRepository
import com.cheyun.netsalev3.utils.CommonFunc
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.view.AddDriveActivity
import com.cheyun.netsalev3.view.ChoiceOrderCustomerActivity
import com.cheyun.netsalev3.view.mars.choosecar.MarsChooseCarActivity
import com.cheyun.netsalev3.widget.DatePickerFragment
import com.cheyun.netsalev3.widget.MyContentDialog
import com.cheyun.netsalev3.widget.MyDialog
import com.cheyun.netsalev3.widget.TimePickerFragment
import com.jeremyliao.liveeventbus.LiveEventBus
import java.io.Serializable
import java.util.*
import kotlin.collections.ArrayList

class EditCustomStoreActivityViewModel(var data: DaoDianDetailsParam, var editCustomStoreRepository: EditCustomStoreRepository) : BaseViewModel() {
    var comtime: String = ""
    var gontime: String = ""
    var activity: AppCompatActivity? = null

    var showDaodian = MutableLiveData<Boolean>(false)
    var checkDaodian = MutableLiveData<String>("")
    var checkDaodianValue = MutableLiveData<Boolean>(false)
    var daodianValue = MutableLiveData<String>()

    var enableEditPhone = MutableLiveData<Boolean>(true)

    var daodianData:OrderKeliuData? = null

    var reserveInfo : ReserveInfo? = null

    init {
        if (data.arrivetime.isNullOrEmpty()) {
            comtime = FunctionUtils.getTime()
            data.arrivetime = comtime
        }
        if(data.id==-1){
            showDaodian.postValue(true)
        }
    }
    var isLoading = false

    var currentContext:Context? = null

    fun onClickOk(view: View) {
//        if(isLoading){
//            Toast.makeText(view.context, "正在提交中", Toast.LENGTH_LONG).show()
//            return;
//        }
        if (data.uname.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入姓名", Toast.LENGTH_LONG).show()
            return
        }
        if (data.arrivetime.isNullOrEmpty()) {
            Toast.makeText(view.context, "请选择到店时间", Toast.LENGTH_LONG).show()
            return
        }
        if (!data.leavetime.isNullOrEmpty()) {
            if(CommonFunc.compareDate(CommonFunc.getDateFormat(data.arrivetime,2),CommonFunc.getDateFormat(data.leavetime,2))<=0){
                Toast.makeText(view.context, "离店时间不能在到店时间之前", Toast.LENGTH_LONG).show()
                return
            }
            if(!CommonFunc.isSameDay(CommonFunc.getDateFormat(data.arrivetime,2),CommonFunc.getDateFormat(data.leavetime,2))){
                Toast.makeText(view.context, "离店时间和到店时间请在同一天", Toast.LENGTH_LONG).show()
                return
            }
        }
        if (data.arrpnum.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入到店人数", Toast.LENGTH_LONG).show()
            return
        }
        if (data.rcvname.isNullOrEmpty()) {
            Toast.makeText(view.context, "请选择接待人", Toast.LENGTH_LONG).show()
            return
        }
        if(checkDaodianValue.value!!){
            if(daodianData == null){
                Toast.makeText(view.context, "请选择到店客流", Toast.LENGTH_LONG).show()
                return
            }
        }
        if(daodianData!=null){
            data.id = daodianData?.id!!
            if(reserveInfo!=null) {
                data.isexit = 1
            }
        }

        var title = ""
        var onSuccess: () -> Unit = {
            isLoading = false
            MyToast(title)
            LiveEventBus.get().with("ReceptionActivity").postValue("ReceptionActivity")
            myFinish()
        }
        isLoading = true
        if (data.id == -1) {
            title = "添加成功"
            editCustomStoreRepository.addData(data, onSuccess)
        } else {
            title = "更新成功"
            editCustomStoreRepository.updateData(data, onSuccess)
        }
    }

    fun onClickDrive(view: View) {
        this.currentContext = view.context

        if (data.uname.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入姓名", Toast.LENGTH_LONG).show()
            return
        }
        if(data.phone.isEmpty()){
            MyToast("试乘试驾必需有客户电话")
            return
        }
        if (data.arrivetime.isNullOrEmpty()) {
            Toast.makeText(view.context, "请选择到店时间", Toast.LENGTH_LONG).show()
            return
        }
        //如果已离店，不能进行试驾
        if(!data.leavetime.isEmpty()){
            MyToast("客户已离店，无法进行试乘试驾")
            return
        }

        if (data.arrpnum.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入到店人数", Toast.LENGTH_LONG).show()
            return
        }
        if (data.rcvname.isNullOrEmpty()) {
            Toast.makeText(view.context, "请选择接待人", Toast.LENGTH_LONG).show()
            return
        }
        if(checkDaodianValue.value!!){
            if(daodianData == null){
                Toast.makeText(view.context, "请选择到店客流", Toast.LENGTH_LONG).show()
                return
            }
        }
        if(daodianData!=null){
            data.id = daodianData?.id!!
            if(reserveInfo!=null) {
                data.adorderid = reserveInfo?.id!!.toInt()
                data.ordertype = reserveInfo?.ordertype.toString()
                data.isexit = 1
            }
        }


        currentdriveArchiveData = null
        editCustomStoreRepository.getArchiveByPhone(data.phone,this::archiveBack)

//        var moth: (d: ReserveInfo) -> Unit = {
//            var intent = Intent(view.context, AddDriveActivity::class.java)
////            if(!it.id.equals("0")) {
////                intent.putExtra("data", it as Serializable)
////            }
//            intent.putExtra("data", it as Serializable)
//            intent.putExtra("keliuData",data)
//            view.context.startActivity(intent)
//        }
//        editCustomStoreRepository.getScanResult(data.phone,data.id.toString(), moth)
    }

    var currentdriveArchiveData:DriveArchiveData? = null

    fun archiveBack(driveArchiveData: DriveArchiveData){
        currentdriveArchiveData = driveArchiveData
        editCustomStoreRepository.getScanResult(data.phone,data.id.toString(), this::getScanResultBack)
    }
    fun getScanResultBack(reserveInfo:ReserveInfo){
        var intent = Intent(currentContext, AddDriveActivity::class.java)
        intent.putExtra("data", reserveInfo as Serializable)
        intent.putExtra("keliuData",data)
        if(currentdriveArchiveData!=null) {
            intent.putExtra("tid", currentdriveArchiveData?.tid)
        }
        currentContext?.startActivity(intent)
    }

    var dataShow = ObservableField<DaoDianDetailsParam>(data)

    fun onClickCancel(view: View) {
        myFinish()
    }

    lateinit var content: AppCompatActivity
    /**
     * 到店
     */
    fun comeTime(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            this.content = content
            var c = Calendar.getInstance()
            this.year = c.get(Calendar.YEAR)
            this.month = c.get(Calendar.MONTH) + 1
            this.day = c.get(Calendar.DAY_OF_MONTH)
            var timePickerFragment = TimePickerFragment()
            timePickerFragment.clickOk = this::comTimeOk
            timePickerFragment.show(content.supportFragmentManager, "")
        }
    }


    var year = 0
    var month = 0
    var day = 0
    /**
     * 到店时间回调
     */
    fun comTimeOk(view: TimePicker, hourOfDay: Int, minute: Int) {
        comtime = FunctionUtils.formatTime(year.toString(), month.toString(), day.toString(), hourOfDay, minute)
        data.arrivetime = comtime
        dataShow.notifyChange()
    }

    /**
     * 离店
     */
    fun goTime(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            this.content = content
            var datePickerFragment = DatePickerFragment()
            datePickerFragment.minDate = Calendar.getInstance().timeInMillis
            datePickerFragment.clickOk = this::goDateOk
            datePickerFragment.show(content.supportFragmentManager, "")
        }
    }

    var year1 = 0
    var month1 = 0
    var day1 = 0
    /**
     * 离店日期回调
     */
    fun goDateOk(view: DatePicker, year: Int, month: Int, day: Int) {
        this.year1 = year
        this.month1 = month
        this.day1 = day
        var timePickerFragment = TimePickerFragment()
        timePickerFragment.clickOk = this::goTimeOk
        timePickerFragment.show(content.supportFragmentManager, "")
    }

    /**
     * 离店时间回调
     */
    fun goTimeOk(view: TimePicker, hourOfDay: Int, minute: Int) {
        gontime = FunctionUtils.formatTime(year1.toString(), month1.toString(), day1.toString(), hourOfDay, minute)

        if (gontime < comtime) {
            MyToast("离店时间不能小于到店时间")
            return
        }
        data.leavetime = gontime
        dataShow.notifyChange()
    }

    var memberlist = ArrayList<Member>()

    init {
        MySharedPreferences.getBaseData()?.member?.apply {
            memberlist.addAll(this)
        }
    }

    /**
     * 点击接待人员
     */
    fun onclickRcvname(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            var list = ArrayList<DialogParam>()
            for (item in memberlist) {
                var dialogParam = DialogParam(item.realname, item.uid.toString())
                list.add(dialogParam)
            }
            var myDialog = MyDialog.newInstance("请选择接待人员", list)
            myDialog.huidia = this::rcvName
            myDialog.show(content.supportFragmentManager, "")
        }
    }

    /**
     * 接待人回调
     */
    fun rcvName(item: DialogParam?) {
        item?.apply {
            data.rcvuid = item.id.toInt()
            data.rcvname = item.name
            dataShow.notifyChange()
        }
    }

    /**
     * 点击是否显示到店客流
     */
    fun onclickShowDiadian(view: View){
        var content = view.context
        if (content is AppCompatActivity) {
            var list = ArrayList<DialogParam>()
            list.add(DialogParam("是", "1"))
            list.add(DialogParam("否", "0"))
            var myDialog = MyDialog.newInstance("是否到店客流", list)
            myDialog.huidia = this::showDaodianCallback
            myDialog.show(content.supportFragmentManager, "")
        }
    }

    /**
     * 是否显示到店客流回调
     */
    fun showDaodianCallback(item: DialogParam?) {
        item?.apply {
            checkDaodian.postValue(if(item?.id.equals("1")) "是" else "否")
            checkDaodianValue.postValue(item?.id.equals("1"))
        }
    }

    /**
     * 点击显示到店客流
     */
    fun onclickDiadian(view: View){
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(content, ChoiceOrderCustomerActivity::class.java)
            intent.putExtra("phone",data.phone)
            intent.putExtra("rcvuid",MySharedPreferences.getLoginData()?.member?.uid.toString())
            if(data.tid>0){
                intent.putExtra("tid",data.tid.toString())
            }
            content.startActivityForResult(intent, 101)
        }
    }

    fun setDaoDaian(item: OrderKeliuData) {
        item?.apply {
            daodianData = item
            if(data.id == -1 ){
                if(reserveInfo == null) {
                    data.phone = item.phone
                    data.uname = item.uname
                }
                data.rcvname = item.rcvname
                data.rcvuid = item.rcvuid
                data.arrivetime = item.arrivetime
            }
            daodianValue.postValue(item.uname)
        }
    }

    /**
     * 品系
     */
    fun onClickBrandname(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            var carBrandParam = CarBrandParam()
            var intent = Intent(content, MarsChooseCarActivity::class.java)
            intent.putExtra("car", carBrandParam)
            intent.putExtra("notop", true)
            intent.putExtra("Isspec", true)
            content.startActivityForResult(intent, 102)
        }
    }

    /**
     * 品牌车系回调
     */
    fun setCarData(carBrandParam: CarBrandParam) {
        carBrandParam?.apply {
            data.brandname = carBrandParam.brandname
            data.seriesname = carBrandParam.seriesname
            data.specname = carBrandParam.specname
            data.brandgroup = carBrandParam.series + "," + carBrandParam.spec
//            dataShow.notifyChange()
        }
    }

    fun getPhone(phone: String, context: AppCompatActivity) {
        this.activity = context
        var moth: (msg:String) -> Unit = {
            if(it.isNotEmpty()){
                activity?.apply {
                    var dialog = MyContentDialog.newInstance("提示", it)
                    dialog.show(this.supportFragmentManager, "")
                }
            }
        }
        editCustomStoreRepository.IsPhone(phone, moth)
    }

    fun setScanData(it: ReserveInfo){
        enableEditPhone.postValue(false)

        data.uname = it.uname
        data.phone = it.phone
        if(it.reserveseries>0) {
            data.series = it.series
            data.seriesname = it.seriesname
            data.brandgroup = it.reserveseries.toString()
        }

        data.adorderid = it.id.toInt()
        data.ordertype = it.ordertype.toString()

        if(it.reservetime!=null){
            data.reservetime = it.reservetime
        }
        data.resid = it.id

        data.openid = it.openid
        data.wxphone = it.wxphone
        if(it.rvtype !=null) {
            data.rvtype = it.rvtype
        }
        data.createway = if(it.createway.equals("")) 0 else it.createway.toInt()

        data.isqrcode = 1

        dataShow.notifyChange()

        reserveInfo = it
    }
}